package so.sao.code.service.infrastructure.context;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import so.sao.code.service.infrastructure.InternalEventStore;
import so.sao.code.service.infrastructure.WebContext;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 事件处理 按base实现 可并发处理
 */

public class MessageContext {
    ExecutorService pool = Executors.newFixedThreadPool(1);
    static Logger log = LoggerFactory.getLogger(MessageContext.class);

    public void execute() {
        pool.execute(new EventConsumer());
    }

    public class EventConsumer implements Runnable {
        @Override
        public void run() {
            BlockingQueue<Object> events = InternalEventStore.getEvents();
            try {
                while (true) {
                    Object event = events.take();
                    if (event != null) {
                        WebContext.publisher.publishEvent(event);
                    }
                }
            } catch (Exception e) {
                log.error("消息处理失败");
            }
        }
    }

}
